<?php

declare(strict_types=1);

namespace App\Dao;

use App\Model\LotteryPrize;
use App\Model\Coupon;
use App\Model\Wxuser;
use App\Model\Lottery;
use App\Utils\StringUtil;

class LotteryPrizeDao
{

    use DaoTrait;

    public function __construct()
    {
        $this->driver = __CLASS__;
    }


    /**
     * 获取奖品列表
     * @param int $limit
     * @param string[] $columns
     * @return array
     */
    public function getList($limit = 8, $columns = ['lottery_prize.id', 'lottery_prize.type', 'lottery_prize.name', 'lottery_prize.img', 'coupon_batch.amount as coupon_amount'])
    {
        return LotteryPrize::query()->leftJoin('coupon_batch', 'lottery_prize.batch_id', '=', 'coupon_batch.id')
            ->where([
                'lottery_prize.status' => 1,
                'lottery_prize.is_del' => 1
            ])->orderBy('lottery_prize.sort', 'desc')
            ->limit($limit)
            ->get($columns)->toArray();
    }

    public function getAllByWhere($map = [])
    {

        return LotteryPrize::query()
            ->with(['couponBatch' => function ($query) {
                $query->select('id', 'name', 'end_time');
            }])
            ->when(!empty($map), function ($query) use ($map) {
                $query->where($map);
            })
            ->ofNotDel()
            ->orderBy('sort', 'desc')
            ->get()->each(function ($value) {
                if (empty($value->couponBatch)) {
                    $bind_name = "未绑定";
                    $remaining_number = 0;
                } else {
                    $bind_name = $value->couponBatch->name;
                    $remaining_number = (time() > $value->couponBatch->end_time) ? 0 : Coupon::where('batch_id', $value->batch_id)->where('status', 0)->count();
                }
                $value->forceFill([
                    'bind_name' => $bind_name,
                    'remaining_number' => $remaining_number
                ])->append(['status_mapping'])->makeHidden(['couponBatch']);
            })->toArray();
    }


    /**
     * 查询
     * @param $where
     * @param string[] $columns
     * @param string $order
     * @param string $direction
     * @return array
     */
    public function findByWhere($where, $columns = ['*'], $order = 'id', $direction = 'desc')
    {
        return LotteryPrize::query()->where($where)->orderBy($order, $direction)->first($columns);
    }

    /**
     * 获取用户抽奖列表
     * @param array $where
     * @param string[] $columns
     * @param int $pageSize
     * @param null $page
     * @return array
     */
    public function getUserListPage($nickname, $where, $pageSize = 15)
    {

        //先查找用户id
        if ($nickname) {
            $ids = Wxuser::query()->when($nickname, function ($query) use ($nickname) {
                $query->whereRaw("from_base64(nickname) LIKE '%" . $nickname . "%'");
            })->pluck('openid');
            $data = Lottery::query()->where($where)->whereIn('openid', $ids)->orderBy('id', 'desc')->paginate(intval($pageSize), ['*'], 'page')->toArray();
            $count = Lottery::query()->where($where)->whereIn('openid', $ids)->count();
        } else {
            $data = Lottery::query()->where($where)->orderBy('id', 'desc')->paginate(intval($pageSize), ['*'], 'page')->toArray();
            $count = Lottery::query()->where($where)->count();
        }

        $list = $data['data'];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $info = Wxuser::query()->where('openid', $v['openid'])->first();

                $list[$k]['nickname'] = $info ? make(StringUtil::class)->strIsBase64($info->nickname) : '';
                $list[$k]['count'] = $v['count'] > 0 ? '+' . $v['count'] : (string) $v['count'];
            }
        }
        unset($data);
        return [
            'data' => $list,
            'count' => $count
        ];
    }

    /**
     * 抽奖记录记录导出
     * @Author czm
     * @DateTime 2020-06-04
     * @param [type] $start_time
     * @param [type] $end_time
     * @return string 
     */
    public function outputLog($map = [], $head = [])
    {
        $this->deleteExpiredFile();
        $file_name = $this->getUniqueName() . '.csv';
        $file_dir = BASE_PATH . $this->getFileDir() . '/' . $file_name;;
        if (!file_exists($file_dir)) {
            touch($file_dir);
        }
        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen($file_dir, 'ab');
        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv("utf-8", "gb2312//IGNORE", $v);
        }
        fputcsv($fp, $head);
        $lock=true;
        $nickname=$map['nickname'];
        $where=$map['where'];
         //先查找用户id
         if ($nickname) {
            $ids = Wxuser::query()->when($nickname, function ($query) use ($nickname) {
                $query->whereRaw("from_base64(nickname) LIKE '%" . $nickname . "%'");
            })->pluck('openid');
            $model = Lottery::query()->where($where)->whereIn('openid', $ids);
        } else {
            $model = Lottery::query()->where($where);
        }

        $model->chunk(3000, function ($items) use ($fp,&$lock) {
            $lock=false;
            $items = $items->toArray();
            foreach ($items as $item) {
                unset($item['is_del']);
                switch ($item['type']) {
                    case 1:
                        $val = '签到';
                        break;
                    case 2:
                        $val = '抽奖';
                        break;
                    case 3:
                        $val = '分享';
                        break;
                    case 4:
                        $val = '充值';
                        break;
                    default:
                        $val = '';
                        break;
                }
                $item['type'] = $val;

                $data = [];
                foreach ($item as $val) {
                    $data[] = strval(iconv("utf-8", "gb2312//IGNORE", " " . strval($val) . " "));
                }
                fputcsv($fp, $data);
            }
            return true;
        });

        if($lock){
            $title=strval(iconv("utf-8", "gb2312//IGNORE", " " . strval("该条件暂无数据") . " "));
            fputcsv($fp, [ $title]);
        }

        fclose($fp);
        return $file_dir;
    }
}
